<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = item.type == 'input_number' ? ['', ''] : ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="title">
          <span
            @click=";(top_index = 1), get_list(), change_header(1)"
            :class="top_index == 1 ? 'select' : ''"
            >充值信息确认</span
          >
          <span
            @click=";(top_index = 2), get_list_1(), change_header(2)"
            :class="top_index == 2 ? 'select' : ''"
            >升级信息确认</span
          >
        </div>
        <div class="flex">
          <!-- <el-button type="primary" @click="show_box = true">新增</el-button> -->

          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        v-if="top_index == 1"
        style="text-align: center"
        :data="list"
        :max-height="max_height"
        border
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: '', order: '' }"
        :row-style="{
          height: height_size == 2 ? '50px' : '',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>

        <el-table-column
          label="付款企业/个人"
          key="付款企业"
          sortable
          v-if="header_list[0].showTable"
          ><template #default="scope: any"
            ><div class="text_over" v-show="scope.row?.enterpriseId != '-1'">
              <el-tooltip
                :content="scope.row?.enterpriseName + ' (企业)'"
                placement="bottom"
              >
                {{ scope.row?.enterpriseName }} (企业)
              </el-tooltip>
            </div>
            <div v-show="scope.row?.enterpriseId == '-1'">
              {{ scope.row?.memberName }} (个人)
            </div>
          </template></el-table-column
        >
        <el-table-column
          label="下单日期"
          key="下单日期"
          sortable
          prop="createTime"
          v-if="header_list[1].showTable"
          ><template #default="scope: any">
            <div>
              {{ formatDate(parseInt(scope.row?.createTime), 'yyyy-MM-dd') }}
            </div>
          </template></el-table-column
        >
        <el-table-column
          label="充值金额"
          key="付款金额"
          sortable
          v-if="header_list[2].showTable"
          prop="totalAmount"
        ></el-table-column>
        <el-table-column
          label="付款金额"
          key="付款金额"
          sortable
          v-if="header_list[3].showTable"
          prop="totalAmount"
        ></el-table-column>
        <el-table-column
          label="充值套餐"
          key="充值套餐"
          sortable
          prop="packageName"
          v-if="header_list[4].showTable"
        >
        </el-table-column>
        <el-table-column
          label="实际到账金额"
          key="实际到账金额"
          sortable
          prop="totalAmount"
          v-if="header_list[5].showTable"
          ><template #default="scope: any">
            {{ scope.row?.giftAmount + scope.row?.totalAmount }}
          </template></el-table-column
        >
        <el-table-column
          label="付款日期"
          key="付款日期"
          sortable
          v-if="header_list[6].showTable"
          prop="updateTime"
          ><template #default="scope: any">
            <div>
              {{ formatDate(parseInt(scope.row?.updateTime), 'yyyy-MM-dd') }}
            </div>
          </template></el-table-column
        >
        <el-table-column
          label="交易单号"
          key="交易单号"
          sortable
          prop="outTradeNo"
          v-if="header_list[7].showTable"
        ></el-table-column>
        <el-table-column
          label="商户单号"
          key="商户单号"
          sortable
          v-if="header_list[8].showTable"
        ></el-table-column>
        <el-table-column
          label="付款备注"
          key="付款备注"
          sortable
          porp="remark"
          v-if="header_list[9].showTable"
          ><template #default="scope: any"
            ><div class="text_over">
              <el-tooltip :content="scope.row?.remark" placement="bottom">
                {{ scope.row?.remark }}
              </el-tooltip>
            </div></template
          ></el-table-column
        >
        <el-table-column
          label="操作"
          width="124px"
          v-if="has_role_list[0].has_role"
        >
          <template #default="scope: any">
            <el-tooltip content="审核" placement="bottom">
              <svgBtn
                icon="table_exam"
                style="font-size: 20px"
                @click="pass(scope.row)"
              ></svgBtn>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-table
        v-if="top_index == 2"
        style="text-align: center"
        :data="list_1"
        :max-height="max_height"
        border
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height: height_size == 2 ? '50px' : '',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>

        <el-table-column
          label="付款企业"
          key="付款企业"
          sortable
          prop="enterpriseName"
          v-if="header_list[0].showTable"
          ><template #default="scope: any"
            ><div class="text_over">
              <el-tooltip
                :content="scope.row?.enterpriseName"
                placement="bottom"
              >
                {{ scope.row?.enterpriseName }}
              </el-tooltip>
            </div></template
          ></el-table-column
        >
        <el-table-column
          label="下单日期"
          key="下单日期"
          sortable
          prop="paySuccessTime"
          v-if="header_list[1].showTable"
          ><template #default="scope: any">
            <div>
              {{
                formatDate(parseInt(scope.row?.paySuccessTime), 'yyyy-MM-dd')
              }}
            </div>
          </template></el-table-column
        >
        <el-table-column
          label="付款金额"
          key="付款金额"
          sortable
          v-if="header_list[2].showTable"
          prop="totalAmount"
        ></el-table-column>

        <el-table-column
          label="升级套餐"
          key="升级套餐"
          sortable
          prop="packageName"
          v-if="header_list[3].showTable"
        >
        </el-table-column>
        <el-table-column
          label="付款日期"
          key="付款日期"
          sortable
          v-if="header_list[4].showTable"
          prop="updateTime"
          ><template #default="scope: any">
            <div>
              {{ formatDate(parseInt(scope.row?.updateTime), 'yyyy-MM-dd') }}
            </div>
          </template></el-table-column
        >
        <el-table-column
          label="交易单号"
          key="交易单号"
          sortable
          v-if="header_list[5].showTable"
          prop="outTradeNo"
        ></el-table-column>
        <el-table-column
          label="商户单号"
          key="商户单号"
          sortable
          prop="outTradeNo"
          v-if="header_list[6].showTable"
        >
          <!-- <template #default="scope: any"><div></div></template> -->
        </el-table-column>
        <el-table-column
          label="操作"
          width="124px"
          v-if="has_role_list[1].has_role"
        >
          <template #default="scope: any">
            <div class="flex_cc gap_20">
              <el-tooltip content="审核" placement="bottom">
                <svgBtn
                  icon="table_exam"
                  style="font-size: 20px"
                  @click="pass(scope.row)"
                ></svgBtn>
              </el-tooltip>
              <el-tooltip
                content="营业执照"
                placement="bottom"
                v-if="
                  scope.row?.businessLicense && scope.row?.businessLicense != ''
                "
              >
                <svgBtn
                  icon="table_info"
                  style="font-size: 20px"
                  @click="download_pic({ item: scope.row, type: 1 })"
                ></svgBtn>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="top_index == 1"
        class="m_10_0 pagination"
        v-model:currentPage="page_data.current"
        v-model:page-size="page_data.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="
          (e) => {
            page_data.pageSize = e
            top_index == 1 ? get_list() : get_list_1()
          }
        "
        @current-change="
          (e) => {
            page_data.current = e
            top_index == 1 ? get_list() : get_list_1()
          }
        "
      />
    </div>
  </div>
  <el-drawer
    v-model="show_confirm_box"
    direction="rtl"
    size="60%"
    :close-on-click-modal="false"
    @close="show_pass_btn = true"
  >
    <template #title
      ><h4 v-if="top_index == 1">充值信息详情</h4>
      <h4 v-else>升级信息详情</h4></template
    >
    <template #default>
      <el-table
        :data="confirm_list"
        border
        style="text-align: center"
        max-height="830px"
      >
        <el-table-column
          label="序号"
          type="index"
          width="80px"
        ></el-table-column>
        <el-table-column label="支付水单号" prop="outTradeNo"></el-table-column>
        <el-table-column label="金额" prop="totalFee"></el-table-column>
        <el-table-column label="付款人" prop="payer"></el-table-column>
        <el-table-column label="付款银行" prop="payBank"></el-table-column>
        <el-table-column label="水单备注">
          <template #default="scope: any"
            ><div class="text_over">
              <el-tooltip :content="scope.row?.payMessage" placement="bottom">
                {{ scope.row?.payMessage }}
              </el-tooltip>
            </div></template
          >
        </el-table-column>
        <el-table-column label="付款水单">
          <template #default="scope: any">
            <div
              v-show="scope.row?.payPic != ''"
              class="cp c_3580eb"
              @click="download_pic({ item: scope.row, type: 2 })"
            >
              预览
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope: any">
            <div>
              <el-radio
                v-model="scope.row.confirmStatus"
                @change="is_right({ item: scope.row, type: 0 })"
                :label="0"
                style="margin: 0"
                >信息无误</el-radio
              >
              <el-radio
                v-model="scope.row.confirmStatus"
                @change="is_right({ item: scope.row, type: 1 })"
                :label="1"
                style="margin: 0"
                >信息有误</el-radio
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="驳回理由" width="200px">
          <template #default="scope: any">
            <el-input
              class="remark"
              :disabled="!scope.row?.confirmStatus"
              v-model="scope.row.remark"
              placeholder="请输入"
              show-word-limit
              maxlength="30"
            ></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="tr m_top10">
        <el-button @click=";(show_confirm_box = false), (show_pass_btn = true)"
          >取消</el-button
        >
        <el-button
          type="warning"
          :loading="btn_loading"
          :disabled="show_reject_btn"
          @click="pass_submit(1)"
          >驳回</el-button
        >
        <el-button
          type="primary"
          :disabled="show_pass_btn"
          :loading="btn_loading"
          @click="pass_submit(2)"
          >审核</el-button
        >
      </div>
    </template>
  </el-drawer>
  <el-image-viewer
    v-if="img_url != ''"
    :url-list="[img_url]"
    fit="scale-down"
    class="border"
    append-to-body
    @close="img_url = ''"
  ></el-image-viewer>
</template>

<script lang="ts" setup>
import { check_role, formatDate, handle_search_key } from '@/utils/utils' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, computed, onBeforeMount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import svgBtn from '@/components/svg_button.vue'
const has_role_list = ref([
  { path: 'rechargeConfirm/pass', has_role: false },
  { path: 'upgradeConfirm/pass', has_role: false },
])
const max_height = ref()
const top_index = ref(1)
const list = ref()
const total = ref()
const loading = ref(false)
const height_size = ref(1)
const recharge_list = ref([]) //套餐列表
const upgrade_list = ref([]) // 升级套餐
const header_list = ref()
const change_header = (e) => {
  console.log(e)
  top_index.value == 1
    ? (page_data_1.value.current = 1)
    : (page_data.value.current = 1)
  header_list.value =
    e == 1
      ? [
          {
            label: '付款企业/个人',
            value: '',
            showTable: true,
            type: 'input',
            isShow: true,
            options: [],
          },
          {
            label: '下单日期',
            value: '',
            showTable: true,
            type: 'date',
            isShow: true,
            options: [],
          },
          {
            label: '充值金额',
            value: ['', ''],
            showTable: true,
            type: 'input_number',
            isShow: false,
            options: [],
          },
          {
            label: '付款金额',
            value: ['', ''],
            showTable: true,
            type: 'input_number',
            isShow: false,
            options: [],
          },
          {
            label: '充值套餐',
            value: '',
            showTable: true,
            type: 'select',
            isShow: false,
            options: computed(() => {
              return recharge_list.value
            }),
          },
          {
            label: '实际到账金额',
            value: ['', ''],
            showTable: true,
            type: 'input_number',
            isShow: false,
            options: [],
          },
          {
            label: '付款日期',
            value: '',
            showTable: true,
            type: 'date',
            isShow: false,
            options: [],
          },
          {
            label: '交易单号',
            value: '',
            showTable: true,
            type: 'input',
            isShow: false,
            options: [],
          },
          {
            label: '商户单号',
            value: '',
            showTable: true,
            type: 'input',
            isShow: false,
            options: [],
          },
          {
            label: '付款备注',
            value: '',
            showTable: true,
            type: 'input',
            isShow: false,
            options: [],
          },
        ]
      : [
          {
            label: '付款企业',
            value: '',
            showTable: true,
            type: 'input',
            isShow: true,
            options: [],
          },
          {
            label: '下单日期',
            value: '',
            showTable: true,
            type: 'date',
            isShow: true,
            options: [],
          },
          {
            label: '付款金额',
            value: ['', ''],
            showTable: true,
            type: 'input_number',
            isShow: false,
            options: [],
          },
          {
            label: '升级套餐',
            value: '',
            showTable: true,
            type: 'select',
            isShow: false,
            options: computed(() => {
              return upgrade_list.value
            }),
          },
          {
            label: '付款日期',
            value: '',
            showTable: true,
            type: 'date',
            isShow: false,
            options: [],
          },
          {
            label: '交易单号',
            value: '',
            showTable: true,
            type: 'input',
            isShow: false,
            options: [],
          },
          {
            label: '商户单号',
            value: '',
            showTable: true,
            type: 'input',
            isShow: false,
            options: [],
          },
        ]
}
const page_data = ref({
  actualAmount: '',
  current: 1,
  giftAmount: '',
  enterpriseName: '',
  memberName: '',
  outTradeNo: '',
  pageSize: 10,
  orderTime: '',
  paymentDate: '',
  packageName: '',
  remark: '',
  paymentAmount: '',
  rechargeAmount: '',
})
const total_1 = ref()
const page_data_1 = ref({
  actualAmount: '',
  current: 1,
  enterpriseName: '',
  outTradeNo: '',
  pageSize: 10,
  createTime: '',
  paySuccessTime: '',
  packageName: '',
  //   remark: '',
})
onBeforeMount(() => {
  change_header(1)
})
onMounted(() => {
  max_height.value = window.innerHeight - 320 // 不带分页的 table 高度
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item.path)
  })
  EventBus.on('refresh', () => {
    get_list() // 充值列表
    get_list_1() // 升级列表
    ElMessage.success('刷新成功！')
  })
  get_recharge_list()
  get_upgrade_list()
  setTimeout(() => {
    get_list()
  })
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const img_url = ref('')
const download_pic = (e) => {
  axios
    .request({
      url:
        e.type == 2
          ? serviceApi.enterprise_downloadSlip + '/' + e.item.payPic
          : serviceApi.enterprise_downloadLicense +
            '/' +
            e.item.businessLicense,
      method: 'get',
      responseType: 'blob',
    })
    .then((res1) => {
      console.log(res1)
      const blob = new Blob([res1 as any]) // res.data 为接口返回的数据，依实例而行
      const URL = window.URL.createObjectURL(blob) // 生成一个 Blob URL
      img_url.value = URL
      //   const fileName =
      //     e.type == 2
      //       ? '支付水单.' + e.item.payPic.split('.').at(-1)
      //       : e.item.enterpriseName +
      //         '-营业执照.' +
      //         e.item.businessLicense.split('.').at(-1)
      //   const listNode = document.createElement('a')
      //   listNode.download = fileName as any
      //   listNode.style.display = 'none'
      //   listNode.href = URL // 文件流生成的url
      //   document.body.appendChild(listNode)
      //   listNode.click() // 模拟在按钮上实现一次鼠标点击
      //   window.URL.revokeObjectURL(listNode.href) // 释放 URL 对象
      //   document.body.removeChild(listNode) // 移除 a 标签
    })
}
const btn_loading = ref(false)
// 审核 e = 1 拒绝  2 通过
const pass_submit = (e) => {
  let IdList = []
  confirm_list.value.forEach((item) => {
    item.itemId = item.id
    IdList.push(item.id)
  })
  console.log(update_item.value)
  let data = {
    enterpriseId: update_item.value.enterpriseId,
    memberId: update_item.value.memberId ? update_item.value.memberId : '',
    payOrderId: update_item.value.payOrderId,
    upgradeOrderId: update_item.value.id,
    rechargeOrderId: update_item.value.id,
    itemList: confirm_list.value, // 拒绝参数
    itemIdList: IdList, // 通过参数
  }
  if (top_index.value == 1) {
    // 充值
    var url =
      e == 1 ? serviceApi.rechangeOrder_reject : serviceApi.rechargeOrder_pass
  } else {
    // 升级
    var url =
      e == 1 ? serviceApi.upgradeOrder_reject : serviceApi.upgradeOrder_pass
  }
  ElMessageBox.confirm(
    top_index.value == 1
      ? '确定审核' + (e == 1 ? '拒绝该充值信息？' : '通过该充值信息？')
      : '确定审核' + (e == 1 ? '拒绝该升级信息？' : '通过该升级信息？'),
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      type: 'warning',
    }
  )
    .then(() => {
      if (btn_loading.value) return
      btn_loading.value = true
      axios
        .request({
          url: url,
          method: 'put',
          data: data,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            btn_loading.value = false
            top_index.value == 2 ? get_list_1() : get_list()
            show_confirm_box.value = false
          }, 1000)
        })
        .catch((err) => {
          btn_loading.value = false
          ElMessage.error(err)
        })
    })
    .catch(() => {
      btn_loading.value = false
    })
}
const show_pass_btn = ref(true)
const show_reject_btn = ref(true)
const is_right = (e) => {
  console.log(e, confirm_list.value)
  let show_pass = confirm_list.value.every((item) => {
    return item.confirmStatus === 0
  })
  let show_error = confirm_list.value.some((item) => {
    return item.confirmStatus === 1
  })
  if (show_pass) {
    show_pass_btn.value = false
  } else {
    show_pass_btn.value = true
  }
  if (show_error) {
    show_reject_btn.value = false
  } else {
    show_reject_btn.value = true
  }
}
const show_confirm_box = ref(false)
const confirm_list = ref([])
const update_item = ref()
const pass = (e) => {
  axios
    .request({
      url:
        top_index.value == 1
          ? serviceApi.rechargeOrder_curd + '/' + e.id
          : serviceApi.upgradeOrder_crud + '/' + e.id,
      method: 'get',
    })
    .then((res) => {
      console.log(res)
      if (res.data.itemList) {
        res.data.itemList.forEach((item) => {
          item.confirmStatus = ''
          item.remark = ''
        })
        show_reject_btn.value = true
        console.log(e)
        update_item.value = res.data
        confirm_list.value = res.data.itemList
        show_confirm_box.value = true
      } else {
        ElMessage.error('该记录数据有误')
      }
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const list_1 = ref()
const get_list_1 = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.upgradeOrder_list,
      method: 'post',
      data: handle_search_key(page_data_1.value),
    })
    .then((res) => {
      console.log(res)
      res.data.content.forEach((item) => {
        if (item.itemList) {
          item.realTotalAmount = 0
          item.itemList.forEach((item1) => {
            item.realTotalAmount += item1.totalFee
          })
        }
      })
      list_1.value = res.data.content
      total_1.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((error) => {
      ElMessage.error(error)
      loading.value = false
    })
}
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.rechargeOrder_list,
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      console.log(res)
      res.data.content.forEach((item) => {
        if (item.itemList) {
          item.realTotalAmount = 0
          item.itemList.forEach((item1) => {
            item.realTotalAmount += item1.totalFee
          })
        }
      })
      list.value = res.data.content
      total.value = parseInt(res.data.totalElements)
      loading.value = false
    })
    .catch((error) => {
      ElMessage.error(error)
      loading.value = false
    })
}
const get_upgrade_list = () => {
  axios
    .request({
      url: serviceApi.upgradePackage_list,
      method: 'post',
      data: { current: 1, pageSize: 1000 },
    })
    .then((res) => {
      console.log(res)
      if (res.data.content.length) {
        res.data.content.forEach((element) => {
          ;(element.label = element.name), (element.value = element.name)
        })
        upgrade_list.value = res.data.content
      }
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const get_recharge_list = () => {
  axios
    .request({
      url: serviceApi.rechargePackage_list,
      method: 'post',
      data: { current: 1, pageSize: 1000 },
    })
    .then((res) => {
      console.log(res)
      res.data.content.forEach((element) => {
        ;(element.label = element.name), (element.value = element.name)
      })
      recharge_list.value = res.data.content
    })
    .catch((error) => {
      ElMessage.error(error)
    })
}
const search_key = () => {
  if (top_index.value == 1) {
    page_data.value = {
      giftAmount: '',
      current: 1,
      pageSize: 10,
      enterpriseName: header_list.value[0].value,
      memberName: header_list.value[0].value,
      orderTime: header_list.value[1].value,
      rechargeAmount: header_list.value[2].value,
      paymentAmount: header_list.value[3].value,
      packageName: header_list.value[4].value,
      actualAmount: header_list.value[5].value,
      paymentDate: header_list.value[6].value,
      outTradeNo: header_list.value[7].value,
      remark: header_list.value[9].value,
    }
    get_list()
  } else {
    page_data_1.value = {
      actualAmount: header_list.value[2].value,
      current: 1,
      enterpriseName: header_list.value[0].value,
      outTradeNo: header_list.value[5].value,
      pageSize: 10,
      createTime: header_list.value[1].value,
      paySuccessTime: header_list.value[4].value,
      packageName: header_list.value[3].value,
      //   remark: header_list.value[0].value,
    }
    get_list_1()
  }
}
</script>

<style lang="scss" scoped>
:deep(.remark .el-input__inner) {
  padding-right: 70px;
}
.title {
  font-weight: bold;
  span {
    cursor: pointer;
    padding: 10px;
  }
  .select {
    color: #3580eb;
  }
}
</style>
